<template>
  <div class="teacher-grade">
    <div class="page-header">
      <h2>📊 成绩管理</h2>
      <p class="page-subtitle">管理学生成绩，支持批量录入、数据导出和统计分析</p>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="学期">
          <el-select
            v-model="filterForm.semester"
            placeholder="请选择学期"
            clearable
            style="width: 180px"
            @change="handleSemesterChange"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程">
          <el-select
            v-model="filterForm.courseId"
            placeholder="请选择课程"
            clearable
            style="width: 180px"
            @change="handleCourseChange"
          >
            <el-option
              v-for="course in courseList"
              :key="course.courseId"
              :label="course.courseName"
              :value="course.courseId"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="班级">
          <el-select
            v-model="filterForm.clazzId"
            placeholder="请选择班级"
            clearable
            style="width: 180px"
            @change="handleFilter"
          >
            <el-option
              v-for="clazz in clazzList"
              :key="clazz.clazzId"
              :label="clazz.clazzName"
              :value="clazz.clazzId"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学生">
          <el-input
            v-model="filterForm.studentName"
            placeholder="学号/姓名"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="filterForm.status"
            placeholder="全部"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" :value="1" />
            <el-option label="待审核" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成绩统计卡片 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :xs="12" :sm="12" :md="6">
        <el-card class="stat-card stat-card-1" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ gradeStats.totalStudents }}</div>
              <div class="stat-label">学生总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="12" :md="6">
        <el-card class="stat-card stat-card-2" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ gradeStats.averageScore }}</div>
              <div class="stat-label">平均分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="12" :md="6">
        <el-card class="stat-card stat-card-3" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ gradeStats.passRate }}%</div>
              <div class="stat-label">及格率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="12" :md="6">
        <el-card class="stat-card stat-card-4" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ gradeStats.excellentRate }}%</div>
              <div class="stat-label">优秀率(≥90分)</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮区 -->
    <el-card class="action-card" shadow="never">
      <el-space wrap>
        <el-button type="success" @click="handleAddByStudentNo" :icon="User">
          通过学号添加
        </el-button>
        <el-button type="success" @click="handleBatchInput" :icon="Edit">
          批量录入
        </el-button>
        <el-button type="warning" @click="handleImport" :icon="Upload">
          导入Excel
        </el-button>
        <el-button type="info" @click="handleExport" :icon="Download">
          导出成绩
        </el-button>
        <el-button @click="handleRefresh" :icon="Refresh">
          刷新
        </el-button>
      </el-space>
    </el-card>

    <!-- 成绩列表 -->
    <el-card class="grade-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>成绩列表 (共 {{ gradeList.length }} 条)</span>
        </div>
      </template>
      
      <div class="grade-content">
        <el-table
          :data="filteredGradeList"
          v-loading="loading"
          stripe
          border
          :row-class-name="getRowClassName"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="studentNo" label="学号" width="105" />
          <el-table-column prop="studentName" label="姓名" width="90" />
          <el-table-column prop="clazzName" label="班级" width="140" show-overflow-tooltip />
          <el-table-column prop="courseName" label="课程" width="140" show-overflow-tooltip />
          
          <el-table-column prop="usualScore" label="平时" width="95" sortable>
            <template #default="{ row }">
              <el-input-number
                v-if="row.editing"
                v-model="row.usualScore"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                style="width: 85px"
                @change="onInlineScoreChange(row)"
              />
              <span v-else :class="getScoreClass(row.usualScore)">
                {{ row.usualScore || '-' }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column prop="midScore" label="期中" width="95" sortable>
            <template #default="{ row }">
              <el-input-number
                v-if="row.editing"
                v-model="row.midScore"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                style="width: 85px"
                @change="onInlineScoreChange(row)"
              />
              <span v-else :class="getScoreClass(row.midScore)">
                {{ row.midScore || '-' }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column prop="finalScore" label="期末" width="95" sortable>
            <template #default="{ row }">
              <el-input-number
                v-if="row.editing"
                v-model="row.finalScore"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                style="width: 85px"
                @change="onInlineScoreChange(row)"
              />
              <span v-else :class="getScoreClass(row.finalScore)">
                {{ row.finalScore || '-' }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column prop="totalScore" label="总评" width="90" sortable>
            <template #default="{ row }">
              <el-tag :type="getTotalScoreType(row.totalScore)" effect="dark" size="small">
                {{ row.totalScore || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="gradePoint" label="绩点" width="70" sortable>
            <template #default="{ row }">
              {{ row.gradePoint || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="gradeLevel" label="等级" width="75">
            <template #default="{ row }">
              <el-tag :type="getLevelType(row.gradeLevel)" size="small">
                {{ row.gradeLevel || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="isPass" label="及格" width="75">
            <template #default="{ row }">
              <el-tag :type="row.isPass ? 'success' : 'danger'" size="small">
                {{ row.isPass ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="isMakeup" label="补考" width="95">
            <template #default="{ row }">
              <el-switch
                v-if="row.editing"
                v-model="row.isMakeup"
                active-text="是"
                inactive-text="否"
                size="small"
              />
              <el-tag v-else-if="row.isMakeup" type="warning" size="small">是</el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="makeupScore" label="补考分" width="100">
            <template #default="{ row }">
              <el-input-number
                v-if="row.editing && row.isMakeup"
                v-model="row.makeupScore"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                style="width: 85px"
              />
              <span v-else-if="row.isMakeup && row.makeupScore" :class="getScoreClass(row.makeupScore)">
                {{ row.makeupScore }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="remark" label="备注" width="180" show-overflow-tooltip>
            <template #default="{ row }">
              <el-input
                v-if="row.editing"
                v-model="row.remark"
                placeholder="备注"
                size="small"
                maxlength="50"
              />
              <span v-else>{{ row.remark || '-' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div v-if="row.editing" style="display: flex; gap: 5px;">
                <el-button type="success" size="small" @click="handleSaveInline(row)" :loading="row.saving">
                  保存
                </el-button>
                <el-button size="small" @click="handleCancelInline(row)">
                  取消
                </el-button>
              </div>
              <div v-else style="display: flex; gap: 5px; justify-content: space-around;">
                <el-button type="primary" size="small" @click="handleStartEdit(row)" link>
                  编辑
                </el-button>
                <el-button type="info" size="small" @click="handleView(row)" link>
                  详情
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)" link>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="gradeList.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 成绩录入/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
      @close="handleDialogClose"
    >
      <el-form
        ref="gradeFormRef"
        :model="gradeForm"
        :rules="gradeRules"
        label-width="110px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学期" prop="semester">
              <el-select
                v-model="gradeForm.semester"
                placeholder="请选择学期"
                style="width: 100%"
                :disabled="isEdit"
              >
                <el-option label="2024春季" value="2024-1" />
                <el-option label="2024秋季" value="2024-2" />
                <el-option label="2025春季" value="2025-1" />
                <el-option label="2025秋季" value="2025-2" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="课程" prop="courseId">
              <el-select
                v-model="gradeForm.courseId"
                placeholder="请选择课程"
                style="width: 100%"
                :disabled="isEdit"
                @change="handleDialogCourseChange"
              >
                <el-option
                  v-for="course in courseList"
                  :key="course.courseId"
                  :label="course.courseName"
                  :value="course.courseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级" prop="clazzId">
              <el-select
                v-model="gradeForm.clazzId"
                placeholder="请选择班级"
                style="width: 100%"
                :disabled="isEdit"
                @change="handleDialogClazzChange"
              >
                <el-option
                  v-for="clazz in dialogClazzList"
                  :key="clazz.clazzId"
                  :label="clazz.clazzName"
                  :value="clazz.clazzId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="学生" prop="studentId">
              <el-select
                v-model="gradeForm.studentId"
                placeholder="请选择学生"
                style="width: 100%"
                :disabled="isEdit"
                filterable
              >
                <el-option
                  v-for="student in dialogStudentList"
                  :key="student.studentId"
                  :label="`${student.studentNo} - ${student.studentName}`"
                  :value="student.studentId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">成绩录入</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="平时成绩" prop="usualScore">
              <el-input-number
                v-model="gradeForm.usualScore"
                :min="0"
                :max="100"
                :precision="1"
                placeholder="0-100"
                style="width: 100%"
                @change="calculateTotalScore"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="期中成绩" prop="midScore">
              <el-input-number
                v-model="gradeForm.midScore"
                :min="0"
                :max="100"
                :precision="1"
                placeholder="0-100"
                style="width: 100%"
                @change="calculateTotalScore"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="期末成绩" prop="finalScore">
              <el-input-number
                v-model="gradeForm.finalScore"
                :min="0"
                :max="100"
                :precision="1"
                placeholder="0-100"
                style="width: 100%"
                @change="calculateTotalScore"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-alert
          title="成绩计算公式"
          type="info"
          :closable="false"
          show-icon
        >
          总评成绩 = 平时成绩 × 30% + 期中成绩 × 30% + 期末成绩 × 40%
        </el-alert>
        
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="8">
            <el-statistic title="总评成绩" :value="calculatedTotal">
              <template #suffix>分</template>
            </el-statistic>
          </el-col>
          <el-col :span="8">
            <el-statistic title="绩点" :value="calculatedGradePoint">
            </el-statistic>
          </el-col>
          <el-col :span="8">
            <el-statistic title="等级">
              <template #formatter>
                <el-tag :type="getLevelType(calculatedLevel)">
                  {{ calculatedLevel }}
                </el-tag>
              </template>
            </el-statistic>
          </el-col>
        </el-row>
        
        <el-form-item label="是否补考" style="margin-top: 20px;">
          <el-switch
            v-model="gradeForm.isMakeup"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        
        <el-form-item v-if="gradeForm.isMakeup" label="补考成绩">
          <el-input-number
            v-model="gradeForm.makeupScore"
            :min="0"
            :max="100"
            :precision="1"
            placeholder="补考成绩"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input
            v-model="gradeForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（选填）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '保存修改' : '确认录入' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量录入对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="批量录入成绩"
      width="95%"
      top="5vh"
    >
      <div class="batch-input-container">
        <el-alert
          title="批量录入说明"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        >
          <p>1. 选择学期、课程和班级后，点击"加载学生"按钮</p>
          <p>2. 在表格中直接输入成绩，总评成绩将自动计算</p>
          <p>3. 成绩计算公式：平时30% + 期中30% + 期末40%</p>
          <p>4. 点击"批量保存"提交所有成绩</p>
        </el-alert>
        
        <el-form :inline="true">
          <el-form-item label="学期">
            <el-select
              v-model="batchForm.semester"
              placeholder="请选择学期"
              style="width: 150px"
            >
              <el-option label="2024春季" value="2024-1" />
              <el-option label="2024秋季" value="2024-2" />
              <el-option label="2025春季" value="2025-1" />
              <el-option label="2025秋季" value="2025-2" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="课程">
            <el-select
              v-model="batchForm.courseId"
              placeholder="请选择课程"
              style="width: 180px"
              @change="handleBatchCourseChange"
            >
              <el-option
                v-for="course in courseList"
                :key="course.courseId"
                :label="course.courseName"
                :value="course.courseId"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="班级">
            <el-select
              v-model="batchForm.clazzId"
              placeholder="请选择班级"
              style="width: 150px"
            >
              <el-option
                v-for="clazz in batchClazzList"
                :key="clazz.clazzId"
                :label="clazz.clazzName"
                :value="clazz.clazzId"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="loadBatchStudents" :loading="batchLoading">
              加载学生
            </el-button>
            <el-button @click="clearBatchData">
              清空数据
            </el-button>
          </el-form-item>
        </el-form>
        
        <el-table
          :data="batchStudentList"
          border
          stripe
          style="width: 100%"
          max-height="450"
          :row-class-name="getBatchRowClass"
        >
          <el-table-column type="index" label="序号" width="60" fixed />
          <el-table-column prop="studentNo" label="学号" width="120" fixed />
          <el-table-column prop="studentName" label="姓名" width="100" fixed />
          
          <el-table-column label="平时成绩" width="130">
            <template #default="{ row }">
              <el-input-number
                v-model="row.usualScore"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                style="width: 100%"
                @change="onBatchScoreChange(row)"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="期中成绩" width="130">
            <template #default="{ row }">
              <el-input-number
                v-model="row.midScore"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                style="width: 100%"
                @change="onBatchScoreChange(row)"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="期末成绩" width="130">
            <template #default="{ row }">
              <el-input-number
                v-model="row.finalScore"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                style="width: 100%"
                @change="onBatchScoreChange(row)"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="总评成绩" width="120">
            <template #default="{ row }">
              <el-tag :type="getTotalScoreType(row.totalScore)" effect="dark">
                {{ row.totalScore || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="绩点" width="80">
            <template #default="{ row }">
              {{ row.gradePoint || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="等级" width="90">
            <template #default="{ row }">
              <el-tag v-if="row.gradeLevel" :type="getLevelType(row.gradeLevel)" size="small">
                {{ row.gradeLevel }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="备注" width="200">
            <template #default="{ row }">
              <el-input
                v-model="row.remark"
                placeholder="备注"
                size="small"
                maxlength="100"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchSubmit" :loading="batchSubmitting">
            批量保存 ({{ batchStudentList.filter(s => s.totalScore).length }} 条)
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成绩详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="成绩详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">
          {{ gradeDetail.studentNo }}
        </el-descriptions-item>
        <el-descriptions-item label="姓名">
          {{ gradeDetail.studentName }}
        </el-descriptions-item>
        <el-descriptions-item label="班级">
          {{ gradeDetail.clazzName }}
        </el-descriptions-item>
        <el-descriptions-item label="课程">
          {{ gradeDetail.courseName }}
        </el-descriptions-item>
        <el-descriptions-item label="学期">
          {{ gradeDetail.semester }}
        </el-descriptions-item>
        <el-descriptions-item label="教师">
          {{ gradeDetail.teacherName }}
        </el-descriptions-item>
        <el-descriptions-item label="平时成绩">
          <span :class="getScoreClass(gradeDetail.usualScore)">
            {{ gradeDetail.usualScore || '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="期中成绩">
          <span :class="getScoreClass(gradeDetail.midScore)">
            {{ gradeDetail.midScore || '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="期末成绩">
          <span :class="getScoreClass(gradeDetail.finalScore)">
            {{ gradeDetail.finalScore || '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="总评成绩">
          <el-tag :type="getTotalScoreType(gradeDetail.totalScore)" effect="dark" size="large">
            {{ gradeDetail.totalScore || '-' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="绩点">
          {{ gradeDetail.gradePoint || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="等级">
          <el-tag :type="getLevelType(gradeDetail.gradeLevel)">
            {{ gradeDetail.gradeLevel || '-' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否及格">
          <el-tag :type="gradeDetail.isPass ? 'success' : 'danger'">
            {{ gradeDetail.isPass ? '及格' : '不及格' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否补考">
          {{ gradeDetail.isMakeup ? '是' : '否' }}
        </el-descriptions-item>
        <el-descriptions-item v-if="gradeDetail.isMakeup" label="补考成绩">
          {{ gradeDetail.makeupScore || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="录入时间" :span="2">
          {{ formatDate(gradeDetail.inputTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">
          {{ formatDate(gradeDetail.updateTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ gradeDetail.remark || '无' }}
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 通过学号添加对话框 -->
    <el-dialog
      v-model="studentNoDialogVisible"
      title="通过学号添加学生成绩"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="studentNoForm" label-width="100px">
        <el-alert
          title="提示"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        >
          请输入您教授课程中学生的学号，系统将自动验证并添加该学生到成绩列表
        </el-alert>

        <el-form-item label="学期" required>
          <el-select
            v-model="studentNoForm.semester"
            placeholder="请选择学期"
            style="width: 100%"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>

        <el-form-item label="课程" required>
          <el-select
            v-model="studentNoForm.courseId"
            placeholder="请选择课程"
            style="width: 100%"
            @change="handleStudentNoCourseChange"
          >
            <el-option
              v-for="course in courseList"
              :key="course.courseId"
              :label="course.courseName"
              :value="course.courseId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="班级" required>
          <el-select
            v-model="studentNoForm.clazzId"
            placeholder="请选择班级"
            style="width: 100%"
          >
            <el-option
              v-for="clazz in studentNoClazzList"
              :key="clazz.clazzId"
              :label="clazz.clazzName"
              :value="clazz.clazzId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学号" required>
          <el-input
            v-model="studentNoForm.studentNo"
            placeholder="请输入学生学号"
            clearable
            @keyup.enter="handleSearchStudent"
          >
            <template #append>
              <el-button
                :icon="Search"
                @click="handleSearchStudent"
                :loading="searchingStudent"
              >
                查询
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <!-- 学生信息显示 -->
        <el-form-item label="学生信息" v-if="foundStudent">
          <el-card shadow="never" style="background: #f5f7fa">
            <el-descriptions :column="2" border size="small">
              <el-descriptions-item label="学号">
                {{ foundStudent.studentNo }}
              </el-descriptions-item>
              <el-descriptions-item label="姓名">
                {{ foundStudent.studentName }}
              </el-descriptions-item>
              <el-descriptions-item label="性别">
                {{ foundStudent.studentGender }}
              </el-descriptions-item>
              <el-descriptions-item label="班级">
                {{ foundStudent.clazzName }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="studentNoDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirmAddStudent"
          :loading="addingStudent"
          :disabled="!foundStudent"
        >
          确认添加
        </el-button>
      </template>
    </el-dialog>

    <!-- 导入Excel对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="📤 导入Excel成绩"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-alert
        title="导入说明"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      >
        <template #default>
          <div style="line-height: 1.8;">
            <p><strong>支持的Excel格式：</strong></p>
            <ol style="margin: 8px 0; padding-left: 20px;">
              <li>必填列：学号、姓名、平时成绩、期中成绩、期末成绩</li>
              <li>可选列：补考（是/否）、补考成绩、备注</li>
              <li>成绩范围：0-100分（支持小数）</li>
              <li>系统会自动计算：总评、绩点、等级</li>
            </ol>
            <p style="margin-top: 8px;">
              <el-link type="primary" @click="downloadTemplate" :icon="Download">
                📥 点击下载Excel模板
              </el-link>
            </p>
          </div>
        </template>
      </el-alert>

      <el-form :model="importForm" label-width="100px">
        <el-form-item label="学期" required>
          <el-select
            v-model="importForm.semester"
            placeholder="请选择学期"
            style="width: 100%"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>

        <el-form-item label="课程" required>
          <el-select
            v-model="importForm.courseId"
            placeholder="请选择课程"
            style="width: 100%"
          >
            <el-option
              v-for="course in courseList"
              :key="course.courseId"
              :label="course.courseName"
              :value="course.courseId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择文件" required>
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            accept=".xlsx,.xls"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="importFileList"
          >
            <el-button type="primary" :icon="Upload">选择Excel文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只支持 .xlsx 或 .xls 格式，文件大小不超过 5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <!-- 数据预览 -->
      <div v-if="importPreviewData.length > 0" style="margin-top: 20px;">
        <el-divider content-position="left">
          <el-icon><View /></el-icon>
          数据预览 (共 {{ importPreviewData.length }} 条)
        </el-divider>
        
        <el-alert
          v-if="importErrorCount > 0"
          :title="`发现 ${importErrorCount} 条错误数据，请检查后重新上传`"
          type="error"
          :closable="false"
          style="margin-bottom: 12px"
        />
        
        <el-table
          :data="importPreviewData.slice(0, 20)"
          border
          stripe
          max-height="400"
          size="small"
        >
          <el-table-column type="index" label="行号" width="60" />
          <el-table-column prop="studentNo" label="学号" width="110" />
          <el-table-column prop="studentName" label="姓名" width="90" />
          <el-table-column prop="usualScore" label="平时" width="80" />
          <el-table-column prop="midScore" label="期中" width="80" />
          <el-table-column prop="finalScore" label="期末" width="80" />
          <el-table-column prop="totalScore" label="总评" width="80">
            <template #default="{ row }">
              <el-tag :type="getTotalScoreType(row.totalScore)" size="small">
                {{ row.totalScore || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="gradeLevel" label="等级" width="80">
            <template #default="{ row }">
              <el-tag :type="getLevelType(row.gradeLevel)" size="small">
                {{ row.gradeLevel || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="error" label="验证结果" min-width="150">
            <template #default="{ row }">
              <el-tag v-if="!row.error" type="success" size="small">✓ 数据正常</el-tag>
              <el-tag v-else type="danger" size="small">✗ {{ row.error }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <div v-if="importPreviewData.length > 20" style="margin-top: 10px; color: #909399; font-size: 12px;">
          <el-icon><InfoFilled /></el-icon>
          只显示前20条数据，实际将导入 {{ importPreviewData.length }} 条数据
        </div>
      </div>

      <template #footer>
        <el-button @click="handleImportCancel">取消</el-button>
        <el-button
          type="primary"
          @click="handleImportConfirm"
          :loading="importSubmitting"
          :disabled="importPreviewData.length === 0 || importErrorCount > 0"
        >
          确认导入 ({{ importPreviewData.filter(d => !d.error).length }} 条)
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Refresh, Edit, Download, Upload, User, Check, Star, Plus, 
  TrendCharts, View, Delete, Close, InfoFilled
} from '@element-plus/icons-vue'
import {
  getTeacherGrades,
  getTeacherCourses,
  getCourseClasses,
  getClassStudents,
  getTeacherStudents,
  addGrade,
  updateGrade,
  deleteGrade,
  batchAddGrades,
  exportGrades
} from '../api/teacherUser'
import ExcelJS from 'exceljs'

// 筛选表单
const filterForm = reactive({
  semester: '2024春季',
  courseId: '',
  clazzId: '',
  studentName: '',
  status: null
})

// 加载状态
const loading = ref(false)
const submitting = ref(false)
const batchLoading = ref(false)
const batchSubmitting = ref(false)

// 数据列表
const gradeList = ref([])
const courseList = ref([])
const clazzList = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20
})

// 过滤后的成绩列表
const filteredGradeList = computed(() => {
  let list = gradeList.value
  
  // 根据学生姓名/学号筛选
  if (filterForm.studentName) {
    list = list.filter(item => 
      item.studentName?.includes(filterForm.studentName) ||
      item.studentNo?.includes(filterForm.studentName)
    )
  }
  
  // 分页
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return list.slice(start, end)
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('录入成绩')
const isEdit = ref(false)
const gradeFormRef = ref(null)

const gradeForm = reactive({
  gradeId: null,
  semester: '2024春季',
  courseId: '',
  clazzId: '',
  studentId: '',
  teacherId: null,
  usualScore: null,
  midScore: null,
  finalScore: null,
  totalScore: null,
  gradePoint: null,
  gradeLevel: '',
  isPass: false,
  isMakeup: false,
  makeupScore: null,
  remark: '',
  status: 1
})

const gradeRules = {
  semester: [{ required: true, message: '请选择学期', trigger: 'change' }],
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  clazzId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  studentId: [{ required: true, message: '请选择学生', trigger: 'change' }]
}

const dialogClazzList = ref([])
const dialogStudentList = ref([])

// 批量录入相关
const batchDialogVisible = ref(false)
const batchForm = reactive({
  semester: '2024春季',
  courseId: '',
  clazzId: '',
  teacherId: null
})
const batchClazzList = ref([])
const batchStudentList = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const gradeDetail = ref({})

// 通过学号添加相关
const studentNoDialogVisible = ref(false)
const studentNoForm = reactive({
  semester: '2024春季',
  courseId: '',
  clazzId: '',
  studentNo: ''
})
const studentNoClazzList = ref([])
const foundStudent = ref(null)
const searchingStudent = ref(false)
const addingStudent = ref(false)

// 选中的行
const selectedRows = ref([])

// 导入Excel相关
const importDialogVisible = ref(false)
const importForm = reactive({
  semester: '2024春季',
  courseId: ''
})
const importFileList = ref([])
const importPreviewData = ref([])
const importSubmitting = ref(false)
const uploadRef = ref(null)

// 导入错误计数
const importErrorCount = computed(() => {
  return importPreviewData.value.filter(item => item.error).length
})

// 计算属性 - 成绩统计
const gradeStats = computed(() => {
  if (gradeList.value.length === 0) {
    return {
      totalStudents: 0,
      averageScore: '0.0',
      passRate: '0.0',
      excellentRate: '0.0'
    }
  }
  
  const total = gradeList.value.length
  const scores = gradeList.value.filter(g => g.totalScore !== null).map(g => parseFloat(g.totalScore))
  
  if (scores.length === 0) {
    return {
      totalStudents: total,
      averageScore: '0.0',
      passRate: '0.0',
      excellentRate: '0.0'
    }
  }
  
  const avg = (scores.reduce((a, b) => a + b, 0) / scores.length).toFixed(1)
  const passCount = scores.filter(s => s >= 60).length
  const excellentCount = scores.filter(s => s >= 90).length
  
  return {
    totalStudents: total,
    averageScore: avg,
    passRate: ((passCount / scores.length) * 100).toFixed(1),
    excellentRate: ((excellentCount / scores.length) * 100).toFixed(1)
  }
})

// 计算总评成绩
const calculatedTotal = computed(() => {
  const { usualScore, midScore, finalScore } = gradeForm
  if (usualScore === null && midScore === null && finalScore === null) return '-'
  
  const usual = usualScore || 0
  const mid = midScore || 0
  const final = finalScore || 0
  
  return (usual * 0.3 + mid * 0.3 + final * 0.4).toFixed(1)
})

// 计算绩点
const calculatedGradePoint = computed(() => {
  const score = parseFloat(calculatedTotal.value)
  if (isNaN(score)) return '-'
  
  if (score >= 90) return '4.0'
  if (score >= 85) return '3.7'
  if (score >= 82) return '3.3'
  if (score >= 78) return '3.0'
  if (score >= 75) return '2.7'
  if (score >= 72) return '2.3'
  if (score >= 68) return '2.0'
  if (score >= 64) return '1.5'
  if (score >= 60) return '1.0'
  return '0.0'
})

// 计算等级
const calculatedLevel = computed(() => {
  const score = parseFloat(calculatedTotal.value)
  if (isNaN(score)) return '-'
  
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 70) return '中等'
  if (score >= 60) return '及格'
  return '不及格'
})

// 获取分数样式类
const getScoreClass = (score) => {
  if (!score && score !== 0) return ''
  const s = parseFloat(score)
  if (s >= 90) return 'score-excellent'
  if (s >= 80) return 'score-good'
  if (s >= 60) return 'score-pass'
  return 'score-fail'
}

// 获取总分标签类型
const getTotalScoreType = (score) => {
  if (!score && score !== 0) return 'info'
  const s = parseFloat(score)
  if (s >= 90) return 'success'
  if (s >= 80) return ''
  if (s >= 60) return 'warning'
  return 'danger'
}

// 获取等级标签类型
const getLevelType = (level) => {
  const typeMap = {
    '优秀': 'success',
    '良好': '',
    '中等': 'warning',
    '及格': 'warning',
    '不及格': 'danger'
  }
  return typeMap[level] || 'info'
}

// 获取批量录入行样式
const getBatchRowClass = ({ row }) => {
  if (row.totalScore) {
    const score = parseFloat(row.totalScore)
    if (score >= 90) return 'row-excellent'
    if (score >= 60) return 'row-pass'
    return 'row-fail'
  }
  return ''
}

// 获取行样式类名 - 用于内联编辑
const getRowClassName = ({ row }) => {
  return row.editing ? 'editing-row' : ''
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 计算总评成绩
const calculateTotalScore = () => {
  const { usualScore, midScore, finalScore } = gradeForm
  if (usualScore !== null || midScore !== null || finalScore !== null) {
    const usual = usualScore || 0
    const mid = midScore || 0
    const final = finalScore || 0
    
    gradeForm.totalScore = parseFloat((usual * 0.3 + mid * 0.3 + final * 0.4).toFixed(1))
    gradeForm.isPass = gradeForm.totalScore >= 60
    
    // 计算绩点
    const score = gradeForm.totalScore
    if (score >= 90) gradeForm.gradePoint = 4.0
    else if (score >= 85) gradeForm.gradePoint = 3.7
    else if (score >= 82) gradeForm.gradePoint = 3.3
    else if (score >= 78) gradeForm.gradePoint = 3.0
    else if (score >= 75) gradeForm.gradePoint = 2.7
    else if (score >= 72) gradeForm.gradePoint = 2.3
    else if (score >= 68) gradeForm.gradePoint = 2.0
    else if (score >= 64) gradeForm.gradePoint = 1.5
    else if (score >= 60) gradeForm.gradePoint = 1.0
    else gradeForm.gradePoint = 0.0
    
    // 设置等级
    if (score >= 90) gradeForm.gradeLevel = '优秀'
    else if (score >= 80) gradeForm.gradeLevel = '良好'
    else if (score >= 70) gradeForm.gradeLevel = '中等'
    else if (score >= 60) gradeForm.gradeLevel = '及格'
    else gradeForm.gradeLevel = '不及格'
  }
}

// 批量录入成绩改变
const onBatchScoreChange = (row) => {
  const { usualScore, midScore, finalScore } = row
  if (usualScore !== null || midScore !== null || finalScore !== null) {
    const usual = usualScore || 0
    const mid = midScore || 0
    const final = finalScore || 0
    
    row.totalScore = parseFloat((usual * 0.3 + mid * 0.3 + final * 0.4).toFixed(1))
    row.isPass = row.totalScore >= 60
    
    // 计算绩点
    const score = row.totalScore
    if (score >= 90) row.gradePoint = 4.0
    else if (score >= 85) row.gradePoint = 3.7
    else if (score >= 82) row.gradePoint = 3.3
    else if (score >= 78) row.gradePoint = 3.0
    else if (score >= 75) row.gradePoint = 2.7
    else if (score >= 72) row.gradePoint = 2.3
    else if (score >= 68) row.gradePoint = 2.0
    else if (score >= 64) row.gradePoint = 1.5
    else if (score >= 60) row.gradePoint = 1.0
    else row.gradePoint = 0.0
    
    // 设置等级
    if (score >= 90) row.gradeLevel = '优秀'
    else if (score >= 80) row.gradeLevel = '良好'
    else if (score >= 70) row.gradeLevel = '中等'
    else if (score >= 60) row.gradeLevel = '及格'
    else row.gradeLevel = '不及格'
  }
}

// 初始化数据 - 从数据库获取
const initData = async () => {
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.id
    
    if (!teacherId) {
      ElMessage.error('请先登录')
      return
    }

    // 获取教师的课程列表
    const coursesRes = await getTeacherCourses(teacherId, filterForm.semester)
    if (coursesRes && coursesRes.data) {
      courseList.value = coursesRes.data
    }
    
    // 如果选择了课程，获取对应的班级列表
    if (filterForm.courseId) {
      const classesRes = await getCourseClasses(teacherId, filterForm.courseId, filterForm.semester)
      if (classesRes && classesRes.data) {
        clazzList.value = classesRes.data
      }
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载课程数据失败')
  }
}

// 获取成绩列表 - 从数据库获取
const fetchGradeList = async () => {
  try {
    loading.value = true
    
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.id
    
    if (!teacherId) {
      ElMessage.error('请先登录')
      loading.value = false
      return
    }

    // 构建查询参数
    const params = {
      semester: filterForm.semester,
      courseId: filterForm.courseId || undefined,
      clazzId: filterForm.clazzId || undefined,
      studentName: filterForm.studentName || undefined,
      status: filterForm.status || undefined,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const res = await getTeacherGrades(teacherId, params)
    
    if (res && res.data) {
      gradeList.value = res.data.records || res.data.list || res.data
      pagination.total = res.data.total || gradeList.value.length
    } else {
      gradeList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取成绩列表失败:', error)
    ElMessage.error('获取成绩列表失败: ' + (error.message || '未知错误'))
    gradeList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 筛选处理 - 学期改变时重新加载课程
const handleSemesterChange = async () => {
  filterForm.courseId = ''
  filterForm.clazzId = ''
  
  // 重新获取课程列表
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  const teacherId = user.teacherId || user.teacher_id || user.id
  
  if (teacherId) {
    try {
      const coursesRes = await getTeacherCourses(teacherId, filterForm.semester)
      if (coursesRes && coursesRes.data) {
        courseList.value = coursesRes.data
      }
    } catch (error) {
      console.error('获取课程列表失败:', error)
    }
  }
  
  handleFilter()
}

const handleCourseChange = async () => {
  filterForm.clazzId = ''
  
  // 重新获取班级列表
  if (filterForm.courseId) {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.id
    
    if (teacherId) {
      try {
        const classesRes = await getCourseClasses(teacherId, filterForm.courseId, filterForm.semester)
        if (classesRes && classesRes.data) {
          clazzList.value = classesRes.data
        }
      } catch (error) {
        console.error('获取班级列表失败:', error)
      }
    }
  }
  
  handleFilter()
}

const handleFilter = () => {
  pagination.currentPage = 1
  fetchGradeList()
}

const handleReset = () => {
  filterForm.semester = '2024春季'
  filterForm.courseId = ''
  filterForm.clazzId = ''
  filterForm.studentName = ''
  filterForm.status = null
  pagination.currentPage = 1
  fetchGradeList()
}

const handleRefresh = () => {
  fetchGradeList()
  ElMessage.success('刷新成功')
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
}

const handlePageChange = (page) => {
  pagination.currentPage = page
}

// 选择行
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增成绩
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '录入成绩'
  resetGradeForm()
  
  // 获取当前教师ID
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  gradeForm.teacherId = user.teacherId || user.teacher_id || user.id
  
  dialogVisible.value = true
}

// ==================== 通过学号添加功能 ====================

// 打开通过学号添加对话框
const handleAddByStudentNo = () => {
  // 重置表单
  studentNoForm.semester = filterForm.semester || '2024春季'
  studentNoForm.courseId = filterForm.courseId || ''
  studentNoForm.clazzId = filterForm.clazzId || ''
  studentNoForm.studentNo = ''
  foundStudent.value = null
  studentNoClazzList.value = []
  
  // 如果已选择课程，加载班级列表
  if (studentNoForm.courseId) {
    loadStudentNoClazzList()
  }
  
  studentNoDialogVisible.value = true
}

// 课程改变时加载班级列表
const handleStudentNoCourseChange = async () => {
  studentNoForm.clazzId = ''
  foundStudent.value = null
  await loadStudentNoClazzList()
}

// 加载班级列表
const loadStudentNoClazzList = async () => {
  if (!studentNoForm.courseId) {
    studentNoClazzList.value = []
    return
  }
  
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.id
    
    const classesRes = await getCourseClasses(teacherId, studentNoForm.courseId, studentNoForm.semester)
    if (classesRes && classesRes.data) {
      studentNoClazzList.value = classesRes.data
    }
  } catch (error) {
    console.error('加载班级列表失败:', error)
    ElMessage.error('加载班级列表失败')
  }
}

// 查询学生
const handleSearchStudent = async () => {
  if (!studentNoForm.semester) {
    ElMessage.warning('请选择学期')
    return
  }
  if (!studentNoForm.courseId) {
    ElMessage.warning('请选择课程')
    return
  }
  if (!studentNoForm.clazzId) {
    ElMessage.warning('请选择班级')
    return
  }
  if (!studentNoForm.studentNo) {
    ElMessage.warning('请输入学号')
    return
  }
  
  try {
    searchingStudent.value = true
    foundStudent.value = null
    
    // 获取该班级的学生列表
    const studentsRes = await getClassStudents(studentNoForm.clazzId, studentNoForm.courseId)
    
    if (studentsRes && studentsRes.data) {
      // 在学生列表中查找匹配的学号
      const student = studentsRes.data.find(s => 
        s.studentNo === studentNoForm.studentNo || 
        String(s.studentNo) === String(studentNoForm.studentNo)
      )
      
      if (student) {
        // 检查是否已经添加过该学生的成绩
        const existingGrade = gradeList.value.find(g => 
          g.studentId === student.studentId && 
          g.courseId === studentNoForm.courseId &&
          g.semester === studentNoForm.semester
        )
        
        if (existingGrade) {
          ElMessage.warning('该学生的成绩已存在，请直接在列表中编辑')
          return
        }
        
        // 找到对应的班级名称
        const clazz = studentNoClazzList.value.find(c => c.clazzId === studentNoForm.clazzId)
        
        foundStudent.value = {
          ...student,
          clazzName: clazz ? clazz.clazzName : '未知班级'
        }
        
        ElMessage.success('学生信息查询成功')
      } else {
        ElMessage.error('未找到该学号的学生，请确认该学生是否在所选班级中')
      }
    }
  } catch (error) {
    console.error('查询学生失败:', error)
    ElMessage.error('查询学生失败: ' + (error.message || '未知错误'))
  } finally {
    searchingStudent.value = false
  }
}

// 确认添加学生
const handleConfirmAddStudent = async () => {
  if (!foundStudent.value) {
    ElMessage.warning('请先查询学生')
    return
  }
  
  try {
    addingStudent.value = true
    
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.id
    
    // 构造成绩数据
    const gradeData = {
      studentId: foundStudent.value.studentId,
      courseId: studentNoForm.courseId,
      clazzId: studentNoForm.clazzId,
      teacherId: teacherId,
      semester: studentNoForm.semester,
      usualScore: null,
      midScore: null,
      finalScore: null,
      totalScore: null,
      gradePoint: null,
      gradeLevel: null,
      isPass: 0,
      isMakeup: 0,
      makeupScore: null,
      remark: '',
      status: 1
    }
    
    // 调用添加成绩API
    await addGrade(gradeData)
    
    ElMessage.success(`成功添加学生 ${foundStudent.value.studentName} (${foundStudent.value.studentNo})`)
    
    // 关闭对话框
    studentNoDialogVisible.value = false
    
    // 刷新列表
    fetchGradeList()
  } catch (error) {
    console.error('添加学生失败:', error)
    ElMessage.error('添加学生失败: ' + (error.message || '未知错误'))
  } finally {
    addingStudent.value = false
  }
}

// 编辑成绩
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑成绩'
  Object.assign(gradeForm, {
    ...row,
    isMakeup: Boolean(row.isMakeup)
  })
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  gradeDetail.value = { ...row }
  detailDialogVisible.value = true
}

// 删除成绩 - 调用真实API
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${row.studentName} (${row.studentNo}) 的 ${row.courseName} 成绩吗？`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteGrade(row.gradeId)
    ElMessage.success('删除成功')
    fetchGradeList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }
}

// ==================== 内联编辑功能 ====================

// 开始编辑
const handleStartEdit = (row) => {
  // 保存原始数据（用于取消时恢复）
  row._originalData = {
    usualScore: row.usualScore,
    midScore: row.midScore,
    finalScore: row.finalScore,
    totalScore: row.totalScore,
    gradePoint: row.gradePoint,
    gradeLevel: row.gradeLevel,
    isMakeup: row.isMakeup,
    makeupScore: row.makeupScore,
    remark: row.remark
  }
  // 设置编辑状态
  row.editing = true
  row.saving = false
}

// 内联编辑时成绩改变 - 自动计算总分
const onInlineScoreChange = (row) => {
  const { usualScore, midScore, finalScore } = row
  if (usualScore !== null || midScore !== null || finalScore !== null) {
    const usual = usualScore || 0
    const mid = midScore || 0
    const final = finalScore || 0
    
    row.totalScore = parseFloat((usual * 0.3 + mid * 0.3 + final * 0.4).toFixed(1))
    row.isPass = row.totalScore >= 60
    
    // 计算绩点
    const score = row.totalScore
    if (score >= 90) row.gradePoint = 4.0
    else if (score >= 85) row.gradePoint = 3.7
    else if (score >= 82) row.gradePoint = 3.3
    else if (score >= 78) row.gradePoint = 3.0
    else if (score >= 75) row.gradePoint = 2.7
    else if (score >= 72) row.gradePoint = 2.3
    else if (score >= 68) row.gradePoint = 2.0
    else if (score >= 64) row.gradePoint = 1.5
    else if (score >= 60) row.gradePoint = 1.0
    else row.gradePoint = 0.0
    
    // 设置等级
    if (score >= 90) row.gradeLevel = '优秀'
    else if (score >= 80) row.gradeLevel = '良好'
    else if (score >= 70) row.gradeLevel = '中等'
    else if (score >= 60) row.gradeLevel = '及格'
    else row.gradeLevel = '不及格'
  }
}

// 保存内联编辑
const handleSaveInline = async (row) => {
  try {
    row.saving = true
    
    // 准备提交数据 - 确保数据类型正确
    const submitData = {
      gradeId: row.gradeId,
      studentId: row.studentId,
      courseId: row.courseId,
      clazzId: row.clazzId,
      teacherId: row.teacherId,
      semester: row.semester,
      usualScore: row.usualScore || null,
      midScore: row.midScore || null,
      finalScore: row.finalScore || null,
      totalScore: row.totalScore || null,
      gradePoint: row.gradePoint || null,
      gradeLevel: row.gradeLevel || null,
      isPass: typeof row.isPass === 'boolean' ? (row.isPass ? 1 : 0) : (row.isPass || 0),
      isMakeup: typeof row.isMakeup === 'boolean' ? (row.isMakeup ? 1 : 0) : (row.isMakeup || 0),
      makeupScore: row.makeupScore || null,
      remark: row.remark || null,
      status: typeof row.status === 'boolean' ? (row.status ? 1 : 0) : (row.status || 1)
    }
    
    console.log('提交的数据:', submitData)
    
    await updateGrade(submitData)
    
    ElMessage.success('保存成功')
    
    // 退出编辑模式
    row.editing = false
    delete row._originalData
    
    // 刷新列表以获取最新数据
    fetchGradeList()
  } catch (error) {
    console.error('保存失败:', error)
    console.error('错误详情:', error.response?.data)
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    row.saving = false
  }
}

// 取消内联编辑
const handleCancelInline = (row) => {
  // 恢复原始数据
  if (row._originalData) {
    row.usualScore = row._originalData.usualScore
    row.midScore = row._originalData.midScore
    row.finalScore = row._originalData.finalScore
    row.totalScore = row._originalData.totalScore
    row.gradePoint = row._originalData.gradePoint
    row.gradeLevel = row._originalData.gradeLevel
    row.isMakeup = row._originalData.isMakeup
    row.makeupScore = row._originalData.makeupScore
    row.remark = row._originalData.remark
    delete row._originalData
  }
  
  // 退出编辑模式
  row.editing = false
  row.saving = false
  
  ElMessage.info('已取消编辑')
}

// 对话框课程改变 - 加载真实班级数据
const handleDialogCourseChange = async () => {
  gradeForm.clazzId = ''
  gradeForm.studentId = ''
  dialogStudentList.value = []
  
  if (!gradeForm.courseId || !gradeForm.teacherId) {
    dialogClazzList.value = []
    return
  }
  
  try {
    const res = await getCourseClasses(gradeForm.teacherId, gradeForm.courseId, gradeForm.semester)
    if (res && res.data) {
      dialogClazzList.value = res.data
    }
  } catch (error) {
    console.error('获取班级列表失败:', error)
    ElMessage.error('获取班级列表失败')
    dialogClazzList.value = []
  }
}

// 对话框班级改变 - 加载真实学生数据
const handleDialogClazzChange = async () => {
  gradeForm.studentId = ''
  
  if (!gradeForm.clazzId || !gradeForm.courseId) {
    console.log('班级或课程未选择:', { clazzId: gradeForm.clazzId, courseId: gradeForm.courseId })
    dialogStudentList.value = []
    return
  }
  
  console.log('开始加载学生列表:', { clazzId: gradeForm.clazzId, courseId: gradeForm.courseId })
  
  try {
    const res = await getClassStudents(gradeForm.clazzId, gradeForm.courseId)
    console.log('API返回的学生数据:', res)
    
    if (res && res.data) {
      dialogStudentList.value = (res.data || []).map(student => ({
        studentId: student.studentId || student.id,
        studentNo: student.studentNo || student.st_no,
        studentName: student.studentName || student.st_name
      }))
      console.log('处理后的学生列表:', dialogStudentList.value)
      ElMessage.success(`加载成功，共 ${dialogStudentList.value.length} 名学生`)
    } else {
      console.warn('API返回为空')
      dialogStudentList.value = []
      ElMessage.warning('该班级暂无学生')
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败: ' + (error.message || '未知错误'))
    dialogStudentList.value = []
  }
}

// 提交成绩 - 调用真实API
const handleSubmit = async () => {
  if (!gradeFormRef.value) return
  
  await gradeFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      
      try {
        // 计算最终成绩
        calculateTotalScore()
        
        // 准备提交数据
        const submitData = {
          ...gradeForm,
          inputBy: gradeForm.teacherId
        }
        
        // 调用API
        if (isEdit.value) {
          await updateGrade(submitData)
          ElMessage.success('修改成绩成功')
        } else {
          await addGrade(submitData)
          ElMessage.success('录入成绩成功')
        }
        
        dialogVisible.value = false
        fetchGradeList()
      } catch (error) {
        console.error('提交成绩失败:', error)
        ElMessage.error((isEdit.value ? '修改' : '录入') + '成绩失败: ' + (error.message || '未知错误'))
      } finally {
        submitting.value = false
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  gradeFormRef.value?.resetFields()
  resetGradeForm()
}

// 重置表单
const resetGradeForm = () => {
  Object.assign(gradeForm, {
    gradeId: null,
    semester: '2024春季',
    courseId: '',
    clazzId: '',
    studentId: '',
    teacherId: null,
    usualScore: null,
    midScore: null,
    finalScore: null,
    totalScore: null,
    gradePoint: null,
    gradeLevel: '',
    isPass: false,
    isMakeup: false,
    makeupScore: null,
    remark: '',
    status: 1
  })
}

// 批量录入
const handleBatchInput = async () => {
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  batchForm.teacherId = user.teacherId || user.teacher_id || user.id
  batchForm.semester = filterForm.semester || '2024春季'
  batchForm.courseId = filterForm.courseId || ''
  batchForm.clazzId = ''
  batchStudentList.value = []
  batchClazzList.value = []
  
  batchDialogVisible.value = true
  
  // 如果已经选择了课程，自动加载班级列表
  if (batchForm.courseId && batchForm.teacherId) {
    try {
      const classesRes = await getCourseClasses(batchForm.teacherId, batchForm.courseId, batchForm.semester)
      if (classesRes && classesRes.data) {
        batchClazzList.value = classesRes.data
      }
    } catch (error) {
      console.error('加载班级列表失败:', error)
    }
  }
}

// 批量课程改变
const handleBatchCourseChange = async () => {
  batchForm.clazzId = ''
  batchStudentList.value = []
  batchClazzList.value = []
  
  if (!batchForm.courseId || !batchForm.teacherId) {
    return
  }
  
  try {
    const classesRes = await getCourseClasses(batchForm.teacherId, batchForm.courseId, batchForm.semester)
    if (classesRes && classesRes.data) {
      batchClazzList.value = classesRes.data
    } else {
      batchClazzList.value = []
    }
  } catch (error) {
    console.error('加载班级列表失败:', error)
    ElMessage.error('加载班级列表失败')
    batchClazzList.value = []
  }
}

// 加载批量学生 - 从数据库获取
const loadBatchStudents = async () => {
  if (!batchForm.semester || !batchForm.courseId || !batchForm.clazzId) {
    ElMessage.warning('请先选择学期、课程和班级')
    return
  }
  
  batchLoading.value = true
  
  try {
    const res = await getClassStudents(batchForm.clazzId, batchForm.courseId)
    
    if (res && res.data) {
      batchStudentList.value = (res.data || []).map(student => ({
        studentId: student.studentId || student.id,
        studentNo: student.stuNo || student.studentNo || student.st_no,
        studentName: student.stuName || student.studentName || student.st_name,
        usualScore: null,
        midScore: null,
        finalScore: null,
        totalScore: null,
        gradePoint: null,
        gradeLevel: '',
        remark: ''
      }))
      
      ElMessage.success(`加载成功，共 ${batchStudentList.value.length} 名学生`)
    } else {
      batchStudentList.value = []
      ElMessage.warning('该班级暂无学生')
    }
  } catch (error) {
    console.error('加载学生失败:', error)
    ElMessage.error('加载学生失败: ' + (error.message || '未知错误'))
    batchStudentList.value = []
  } finally {
    batchLoading.value = false
  }
}

// 清空批量数据
const clearBatchData = () => {
  batchStudentList.value = []
}

// 批量提交 - 调用真实API
const handleBatchSubmit = async () => {
  // 验证必填项
  if (!batchForm.semester || !batchForm.courseId || !batchForm.clazzId || !batchForm.teacherId) {
    ElMessage.warning('请先选择学期、课程和班级')
    return
  }
  
  const validData = batchStudentList.value.filter(s => s.totalScore !== null)
  
  if (validData.length === 0) {
    ElMessage.warning('请至少录入一条成绩')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要提交 ${validData.length} 条成绩吗？`,
      '批量提交确认',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    batchSubmitting.value = true
    
    // 准备批量数据 - 确保数据类型正确
    const gradesData = validData.map(student => ({
      studentId: student.studentId,
      courseId: batchForm.courseId,
      clazzId: batchForm.clazzId,
      teacherId: batchForm.teacherId,
      semester: batchForm.semester,
      usualScore: student.usualScore || null,
      midScore: student.midScore || null,
      finalScore: student.finalScore || null,
      totalScore: student.totalScore || null,
      gradePoint: student.gradePoint || null,
      gradeLevel: student.gradeLevel || null,
      isPass: typeof student.isPass === 'boolean' ? (student.isPass ? 1 : 0) : (student.isPass || 0),
      isMakeup: 0,
      makeupScore: null,
      remark: student.remark || null,
      inputBy: batchForm.teacherId,
      status: 1
    }))
    
    console.log('批量提交数据:', gradesData)
    console.log('batchForm:', batchForm)
    
    await batchAddGrades(gradesData)
    
    ElMessage.success(`批量录入成功，共 ${validData.length} 条`)
    batchDialogVisible.value = false
    batchStudentList.value = []
    fetchGradeList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量提交失败:', error)
      ElMessage.error('批量提交失败: ' + (error.message || '未知错误'))
    }
  } finally {
    batchSubmitting.value = false
  }
}

// 导入Excel - 打开对话框
const handleImport = () => {
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  importForm.semester = filterForm.semester || '2024春季'
  importForm.courseId = filterForm.courseId || ''
  importForm.teacherId = user.teacherId || user.teacher_id || user.id
  importFileList.value = []
  importPreviewData.value = []
  importDialogVisible.value = true
}

// 文件选择改变
const handleFileChange = async (file) => {
  if (!importForm.semester || !importForm.courseId) {
    ElMessage.warning('请先选择学期和课程')
    importFileList.value = []
    return
  }
  
  // 检查文件大小
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过 5MB')
    importFileList.value = []
    return
  }
  
  // 检查文件类型
  const fileName = file.name
  if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
    ElMessage.error('只支持 .xlsx 或 .xls 格式的Excel文件')
    importFileList.value = []
    return
  }
  
  // 读取并解析Excel
  try {
    const arrayBuffer = await file.raw.arrayBuffer()
    const workbook = new ExcelJS.Workbook()
    await workbook.xlsx.load(arrayBuffer)
    
    // 读取第一个工作表
    const worksheet = workbook.worksheets[0]
    if (!worksheet) {
      ElMessage.error('Excel文件为空')
      return
    }
    
    // 解析数据
    const data = []
    const headers = []
    
    // 读取表头（前5行自动检测）
    let headerRow = null
    let dataStartRow = 2
    
    // 尝试查找表头行（检查前5行）
    for (let rowNumber = 1; rowNumber <= Math.min(5, worksheet.rowCount); rowNumber++) {
      const row = worksheet.getRow(rowNumber)
      const firstCellValue = row.getCell(1).value?.toString().trim()
      const secondCellValue = row.getCell(2).value?.toString().trim()
      
      // 检查是否包含"序号"、"学号"或"姓名"等关键字
      if (firstCellValue === '序号' || firstCellValue === '学号' || 
          secondCellValue === '学号' || secondCellValue === '姓名') {
        headerRow = row
        dataStartRow = rowNumber + 1
        console.log(`找到表头在第${rowNumber}行`)
        break
      }
    }
    
    if (!headerRow) {
      // 默认使用第一行
      console.warn('未找到标准表头，使用第1行作为表头')
      headerRow = worksheet.getRow(1)
      dataStartRow = 2
    }
    
    // 读取表头
    headerRow.eachCell((cell, colNumber) => {
      headers[colNumber] = cell.value?.toString().trim() || ''
    })
    
    console.log('Excel表头:', headers)
    
    // 查找列索引
    const columnMap = {
      studentNo: -1,
      studentName: -1,
      usualScore: -1,
      midScore: -1,
      finalScore: -1,
      isMakeup: -1,
      makeupScore: -1,
      remark: -1
    }
    
    headers.forEach((header, index) => {
      if (header.includes('学号')) columnMap.studentNo = index
      else if (header.includes('姓名')) columnMap.studentName = index
      else if (header.includes('平时')) columnMap.usualScore = index
      else if (header.includes('期中')) columnMap.midScore = index
      else if (header.includes('期末')) columnMap.finalScore = index
      else if (header.includes('补考') && !header.includes('成绩') && !header.includes('分')) columnMap.isMakeup = index
      else if (header.includes('补考') && (header.includes('成绩') || header.includes('分'))) columnMap.makeupScore = index
      else if (header.includes('备注')) columnMap.remark = index
    })
    
    console.log('列映射:', columnMap)
    
    // 验证必填列
    if (columnMap.studentNo === -1 || columnMap.studentName === -1) {
      ElMessage.error('Excel文件缺少必填列：学号、姓名')
      return
    }
    
    // 读取数据行
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber < dataStartRow) return
      
      const studentNo = row.getCell(columnMap.studentNo).value?.toString().trim()
      if (!studentNo) return // 跳过空行
      
      const rowData = {
        studentNo: studentNo,
        studentName: row.getCell(columnMap.studentName).value?.toString().trim() || '',
        usualScore: parseFloat(row.getCell(columnMap.usualScore).value) || null,
        midScore: parseFloat(row.getCell(columnMap.midScore).value) || null,
        finalScore: parseFloat(row.getCell(columnMap.finalScore).value) || null,
        isMakeup: false,
        makeupScore: null,
        remark: row.getCell(columnMap.remark).value?.toString().trim() || '',
        error: '' // 错误信息
      }
      
      // 补考信息
      if (columnMap.isMakeup !== -1) {
        const makeupValue = row.getCell(columnMap.isMakeup).value?.toString().trim()
        rowData.isMakeup = makeupValue === '是' || makeupValue === 'true' || makeupValue === '1'
      }
      if (columnMap.makeupScore !== -1) {
        rowData.makeupScore = parseFloat(row.getCell(columnMap.makeupScore).value) || null
      }
      
      // 验证数据
      if (!rowData.studentNo) {
        rowData.error = '学号不能为空'
      } else if (!rowData.studentName) {
        rowData.error = '姓名不能为空'
      } else if (rowData.usualScore !== null && (rowData.usualScore < 0 || rowData.usualScore > 100)) {
        rowData.error = '平时成绩必须在0-100之间'
      } else if (rowData.midScore !== null && (rowData.midScore < 0 || rowData.midScore > 100)) {
        rowData.error = '期中成绩必须在0-100之间'
      } else if (rowData.finalScore !== null && (rowData.finalScore < 0 || rowData.finalScore > 100)) {
        rowData.error = '期末成绩必须在0-100之间'
      } else if (rowData.makeupScore !== null && (rowData.makeupScore < 0 || rowData.makeupScore > 100)) {
        rowData.error = '补考成绩必须在0-100之间'
      }
      
      // 计算总评、绩点、等级
      if (!rowData.error && (rowData.usualScore !== null || rowData.midScore !== null || rowData.finalScore !== null)) {
        const usual = rowData.usualScore || 0
        const mid = rowData.midScore || 0
        const final = rowData.finalScore || 0
        
        rowData.totalScore = parseFloat((usual * 0.3 + mid * 0.3 + final * 0.4).toFixed(1))
        rowData.isPass = rowData.totalScore >= 60
        
        // 计算绩点
        const score = rowData.totalScore
        if (score >= 90) rowData.gradePoint = 4.0
        else if (score >= 85) rowData.gradePoint = 3.7
        else if (score >= 82) rowData.gradePoint = 3.3
        else if (score >= 78) rowData.gradePoint = 3.0
        else if (score >= 75) rowData.gradePoint = 2.7
        else if (score >= 72) rowData.gradePoint = 2.3
        else if (score >= 68) rowData.gradePoint = 2.0
        else if (score >= 64) rowData.gradePoint = 1.5
        else if (score >= 60) rowData.gradePoint = 1.0
        else rowData.gradePoint = 0.0
        
        // 设置等级
        if (score >= 90) rowData.gradeLevel = '优秀'
        else if (score >= 80) rowData.gradeLevel = '良好'
        else if (score >= 70) rowData.gradeLevel = '中等'
        else if (score >= 60) rowData.gradeLevel = '及格'
        else rowData.gradeLevel = '不及格'
      }
      
      data.push(rowData)
    })
    
    if (data.length === 0) {
      ElMessage.error('Excel文件没有有效数据')
      return
    }
    
    importPreviewData.value = data
    const errorCount = data.filter(d => d.error).length
    
    if (errorCount > 0) {
      ElMessage.warning(`解析完成，发现 ${errorCount} 条错误数据，请检查后重新上传`)
    } else {
      ElMessage.success(`解析成功，共 ${data.length} 条数据`)
    }
  } catch (error) {
    console.error('解析Excel失败:', error)
    ElMessage.error('解析Excel文件失败: ' + error.message)
    importFileList.value = []
  }
}

// 文件移除
const handleFileRemove = () => {
  importPreviewData.value = []
}

// 取消导入
const handleImportCancel = () => {
  importDialogVisible.value = false
  importFileList.value = []
  importPreviewData.value = []
}

// 🔥 确认导入 - 全新实现
const handleImportConfirm = async () => {
  console.log('\n='.repeat(50))
  console.log('📤 开始成绩导入流程')
  console.log('='.repeat(50))
  
  // 1. 验证基本信息
  if (!importForm.semester || !importForm.courseId) {
    ElMessage.warning('请先选择学期和课程')
    return
  }
  
  // 2. 获取有效数据
  const validData = importPreviewData.value.filter(item => !item.error)
  if (validData.length === 0) {
    ElMessage.warning('没有有效数据可导入')
    return
  }
  
  console.log(`\n✅ 准备导入 ${validData.length} 条数据`)
  console.table(validData.map(item => ({
    学号: item.studentNo,
    姓名: item.studentName,
    平时: item.usualScore,
    期中: item.midScore,
    期末: item.finalScore,
    总评: item.totalScore
  })))
  
  // 3. 确认对话框
  try {
    await ElMessageBox.confirm(
      `确定要导入 ${validData.length} 条成绩数据吗？`,
      '确认导入',
      {
        confirmButtonText: '确定导入',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    console.log('❌ 用户取消导入')
    return
  }
  
  importSubmitting.value = true
  
  try {
    // 4. 获取用户信息
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.id
    
    if (!teacherId) {
      throw new Error('无法获取教师ID，请重新登录')
    }
    
    console.log(`\n👤 教师ID: ${teacherId}`)
    console.log(`📅 学期: ${importForm.semester}`)
    console.log(`📚 课程ID: ${importForm.courseId}`)
    
    // 5. 获取教师的学生列表
    console.log('\n🔍 正在获取学生信息...')
    const studentsRes = await getTeacherStudents(teacherId, importForm.semester)
    
    if (!studentsRes || !studentsRes.data || studentsRes.data.length === 0) {
      throw new Error('未找到该教师的学生列表，请确认您有权限管理这些学生')
    }
    
    console.log(`✅ 获取到 ${studentsRes.data.length} 个学生`)
    
    // 6. 建立学号到学生信息的映射
    const studentMap = new Map()
    studentsRes.data.forEach(student => {
      const stuNo = String(student.stuNo || student.studentNo || '')
      if (stuNo) {
        studentMap.set(stuNo, {
          studentId: student.studentId || student.id,
          clazzId: student.clazzId || student.clazz_id,
          stuName: student.stuName || student.studentName
        })
      }
    })
    
    console.log(`\n📊 学号映射表已建立 (共 ${studentMap.size} 个)`)
    
    // 7. 构建成绩数据
    console.log('\n🔨 开始构建成绩数据...')
    const gradesData = []
    const errors = []
    
    validData.forEach((item, index) => {
      const stuNo = String(item.studentNo)
      const studentInfo = studentMap.get(stuNo)
      
      if (!studentInfo) {
        console.warn(`  ⚠️  第 ${index + 1} 行：未找到学号 ${stuNo}`)
        errors.push(`学号 ${stuNo} (${item.studentName}) 不在您的学生列表中`)
        return
      }
      
      // 构建Grade对象
      const grade = {
        // 关联信息
        studentId: studentInfo.studentId,
        clazzId: studentInfo.clazzId,
        courseId: Number(importForm.courseId),
        teacherId: Number(teacherId),
        semester: importForm.semester,
        
        // 成绩信息
        usualScore: item.usualScore != null ? Number(item.usualScore) : null,
        midScore: item.midScore != null ? Number(item.midScore) : null,
        finalScore: item.finalScore != null ? Number(item.finalScore) : null,
        totalScore: item.totalScore != null ? Number(item.totalScore) : null,
        gradePoint: item.gradePoint != null ? Number(item.gradePoint) : null,
        gradeLevel: item.gradeLevel || null,
        
        // 及格和补考
        isPass: item.isPass ? 1 : 0,
        isMakeup: item.isMakeup ? 1 : 0,
        makeupScore: item.makeupScore != null ? Number(item.makeupScore) : null,
        
        // 其他信息
        remark: item.remark || null,
        inputBy: Number(teacherId),
        status: 1
      }
      
      gradesData.push(grade)
      console.log(`  ✅  第 ${index + 1} 行：${stuNo} (${studentInfo.stuName}) 数据已准备`)
    })
    
    // 8. 处理错误
    if (errors.length > 0) {
      console.error('\n❌ 发现以下问题:')
      errors.forEach((err, i) => console.error(`  ${i + 1}. ${err}`))
      
      if (gradesData.length === 0) {
        throw new Error(`所有学号都无效\n\n${errors.slice(0, 5).join('\n')}`)
      }
      
      // 部分失败，询问是否继续
      try {
        await ElMessageBox.confirm(
          `有 ${errors.length} 条数据无效，是否继续导入剩余 ${gradesData.length} 条？\n\n无效数据:\n${errors.slice(0, 3).join('\n')}${errors.length > 3 ? '\n...' : ''}`,
          '部分数据无效',
          {
            confirmButtonText: `继续导入 ${gradesData.length} 条`,
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
      } catch {
        throw new Error('导入已取消')
      }
    }
    
    // 9. 发送到后端
    console.log(`\n📤 正在提交 ${gradesData.length} 条数据到服务器...`)
    console.log('请求数据（前2条）:', JSON.stringify(gradesData.slice(0, 2), null, 2))
    
    const result = await batchAddGrades(gradesData)
    
    console.log('✅ 服务器响应:', result)
    
    // 10. 成功提示
    let successMsg
    if (errors.length > 0) {
      // 有跳过的数据
      successMsg = `成功处理 ${gradesData.length} 条数据（${errors.length} 条跳过）`
    } else {
      // 全部成功，根据实际操作显示
      successMsg = `成功导入 ${gradesData.length} 条成绩数据！`
    }
    
    // 如果后端返回了更详细的信息，可以进一步优化提示
    if (result && result.message) {
      console.log('后端消息:', result.message)
    }
    
    ElMessage.success(successMsg)
    console.log('\n' + '='.repeat(50))
    console.log(`🎉 ${successMsg}`)
    console.log('💡 提示：重复导入会自动更新已有成绩')
    console.log('='.repeat(50) + '\n')
    
    // 11. 关闭对话框并刷新
    importDialogVisible.value = false
    importFileList.value = []
    importPreviewData.value = []
    await fetchGradeList()
    
  } catch (error) {
    console.error('\n' + '='.repeat(50))
    console.error('❌ 导入失败')
    console.error('='.repeat(50))
    console.error('错误类型:', error.constructor.name)
    console.error('错误消息:', error.message)
    console.error('完整错误:', error)
    console.error('='.repeat(50) + '\n')
    
    if (error.message === '导入已取消') {
      ElMessage.info('已取消导入')
    } else {
      ElMessage.error('导入失败: ' + error.message)
    }
  } finally {
    importSubmitting.value = false
  }
}

// 下载导入模板
const downloadTemplate = async () => {
  try {
    const workbook = new ExcelJS.Workbook()
    workbook.creator = '排课管理系统'
    workbook.created = new Date()
    
    const sheet = workbook.addWorksheet('成绩导入模板')
    
    // 设置列宽
    sheet.columns = [
      { width: 8 },   // 序号
      { width: 12 },  // 学号
      { width: 12 },  // 姓名
      { width: 10 },  // 平时
      { width: 10 },  // 期中
      { width: 10 },  // 期末
      { width: 8 },   // 补考
      { width: 10 },  // 补考成绩
      { width: 20 }   // 备注
    ]
    
    // 标题行
    sheet.mergeCells('A1:I1')
    const titleCell = sheet.getCell('A1')
    titleCell.value = '成绩导入模板 - 请从第3行开始填写数据'
    titleCell.font = { bold: true, size: 14, color: { argb: 'FF2C3E50' } }
    titleCell.alignment = { vertical: 'middle', horizontal: 'center' }
    titleCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF0F2F5' } }
    sheet.getRow(1).height = 30
    
    // 表头行
    const headerRow = sheet.addRow(['序号', '学号', '姓名', '平时成绩', '期中成绩', '期末成绩', '补考', '补考成绩', '备注'])
    headerRow.height = 25
    headerRow.font = { bold: true, size: 11, color: { argb: 'FFFFFFFF' } }
    headerRow.alignment = { vertical: 'middle', horizontal: 'center' }
    headerRow.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF5470C6' } }
    
    // 示例数据
    const examples = [
      [1, '20230001', '张三', 85, 90, 88, '否', '', '优秀学生'],
      [2, '20230002', '李四', 78, 82, 80, '否', '', ''],
      [3, '20230003', '王五', 55, 58, 50, '是', 65, '补考通过']
    ]
    
    examples.forEach((example, index) => {
      const row = sheet.addRow(example)
      row.height = 22
      row.alignment = { vertical: 'middle', horizontal: 'center' }
      row.getCell(9).alignment = { vertical: 'middle', horizontal: 'left' }
      
      // 斑马纹
      if (index % 2 === 1) {
        row.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF9FAFB' } }
      }
    })
    
    // 添加边框
    sheet.eachRow((row, rowNumber) => {
      if (rowNumber >= 1) {
        row.eachCell((cell) => {
          cell.border = {
            top: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            left: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            bottom: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            right: { style: 'thin', color: { argb: 'FFD0D0D0' } }
          }
        })
      }
    })
    
    // 添加说明
    sheet.addRow([])
    const noteRow1 = sheet.addRow(['说明：'])
    noteRow1.getCell(1).font = { bold: true, size: 11, color: { argb: 'FFFF0000' } }
    
    const notes = [
      '1. 请从第3行开始填写学生成绩数据',
      '2. 必填列：学号、姓名、平时成绩、期中成绩、期末成绩',
      '3. 成绩范围：0-100分（支持小数，如85.5）',
      '4. 补考列：填写"是"或"否"',
      '5. 总评成绩、绩点、等级会自动计算，无需填写',
      '6. 删除示例数据后开始填写实际学生成绩'
    ]
    
    notes.forEach(note => {
      const noteRow = sheet.addRow([note])
      noteRow.getCell(1).font = { size: 10, color: { argb: 'FF606266' } }
      sheet.mergeCells(noteRow.number, 1, noteRow.number, 9)
    })
    
    const fileName = `成绩导入模板_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`
    
    const buffer = await workbook.xlsx.writeBuffer()
    const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('模板下载成功！')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败: ' + error.message)
  }
}

// 导出成绩 - 使用ExcelJS生成精美Excel
const handleExport = async () => {
  if (gradeList.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }
  
  try {
    // 获取当前用户信息
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherName = user.teName || user.name || '教师'
    
    // 创建工作簿
    const workbook = new ExcelJS.Workbook()
    workbook.creator = teacherName
    workbook.created = new Date()
    
    // ================ 工作表1：成绩列表 ================
    const sheet1 = workbook.addWorksheet('成绩列表')
    
    // 设置列宽
    sheet1.columns = [
      { width: 8 },   // 序号
      { width: 12 },  // 学号
      { width: 12 },  // 姓名
      { width: 16 },  // 班级
      { width: 16 },  // 课程
      { width: 10 },  // 平时
      { width: 10 },  // 期中
      { width: 10 },  // 期末
      { width: 10 },  // 总评
      { width: 8 },   // 绩点
      { width: 10 },  // 等级
      { width: 8 },   // 及格
      { width: 8 },   // 补考
      { width: 10 },  // 补考分
      { width: 20 }   // 备注
    ]
    
    // 添加标题（合并单元格）
    sheet1.mergeCells('A1:O1')
    const titleCell = sheet1.getCell('A1')
    const courseName = filterForm.courseId 
      ? (courseList.value.find(c => c.courseId === filterForm.courseId)?.courseName || '全部课程')
      : '全部课程'
    const clazzName = filterForm.clazzId 
      ? (clazzList.value.find(c => c.clazzId === filterForm.clazzId)?.clazzName || '')
      : ''
    titleCell.value = `${filterForm.semester}学期 ${courseName}${clazzName ? ' - ' + clazzName : ''} 成绩表`
    titleCell.font = { bold: true, size: 18, color: { argb: 'FF2C3E50' } }
    titleCell.alignment = { vertical: 'middle', horizontal: 'center' }
    titleCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFF0F2F5' }
    }
    sheet1.getRow(1).height = 40
    
    // 添加统计信息行
    sheet1.mergeCells('A2:E2')
    const statsCell = sheet1.getCell('A2')
    statsCell.value = `学生总数: ${gradeStats.value.totalStudents}   平均分: ${gradeStats.value.averageScore}   及格率: ${gradeStats.value.passRate}%   优秀率: ${gradeStats.value.excellentRate}%`
    statsCell.font = { size: 11, color: { argb: 'FF606266' } }
    statsCell.alignment = { vertical: 'middle', horizontal: 'left' }
    statsCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFAFBFC' }
    }
    sheet1.getRow(2).height = 25
    
    // 添加导出信息
    sheet1.mergeCells('F2:O2')
    const exportInfoCell = sheet1.getCell('F2')
    exportInfoCell.value = `导出教师: ${teacherName}   导出时间: ${new Date().toLocaleString('zh-CN')}`
    exportInfoCell.font = { size: 11, color: { argb: 'FF606266' } }
    exportInfoCell.alignment = { vertical: 'middle', horizontal: 'right' }
    exportInfoCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFAFBFC' }
    }
    
    // 添加表头
    const headerRow = sheet1.addRow([
      '序号', '学号', '姓名', '班级', '课程', 
      '平时', '期中', '期末', '总评', '绩点', '等级', '及格', '补考', '补考分', '备注'
    ])
    headerRow.height = 30
    headerRow.font = { bold: true, size: 11, color: { argb: 'FFFFFFFF' } }
    headerRow.alignment = { vertical: 'middle', horizontal: 'center' }
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF667EEA' }
    }
    
    // 添加成绩数据
    gradeList.value.forEach((grade, index) => {
      const row = sheet1.addRow([
        index + 1,
        grade.studentNo || '',
        grade.studentName || '',
        grade.clazzName || '',
        grade.courseName || '',
        grade.usualScore || '-',
        grade.midScore || '-',
        grade.finalScore || '-',
        grade.totalScore || '-',
        grade.gradePoint || '-',
        grade.gradeLevel || '-',
        grade.isPass ? '是' : '否',
        grade.isMakeup ? '是' : '否',
        grade.makeupScore || '-',
        grade.remark || ''
      ])
      
      row.height = 24
      row.alignment = { vertical: 'middle', horizontal: 'center' }
      
      // 序号列加粗
      row.getCell(1).font = { bold: true }
      
      // 备注列左对齐
      row.getCell(15).alignment = { vertical: 'middle', horizontal: 'left' }
      
      // 根据分数设置颜色
      const totalScore = parseFloat(grade.totalScore)
      if (!isNaN(totalScore)) {
        // 平时、期中、期末成绩单元格
        [6, 7, 8].forEach(colIndex => {
          const cell = row.getCell(colIndex)
          const score = parseFloat(cell.value)
          if (!isNaN(score)) {
            if (score >= 90) {
              cell.font = { color: { argb: 'FF67C23A' }, bold: true }
            } else if (score >= 80) {
              cell.font = { color: { argb: 'FF409EFF' }, bold: true }
            } else if (score >= 60) {
              cell.font = { color: { argb: 'FFE6A23C' }, bold: true }
            } else {
              cell.font = { color: { argb: 'FFF56C6C' }, bold: true }
            }
          }
        })
        
        // 总评成绩单元格
        const totalCell = row.getCell(9)
        if (totalScore >= 90) {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFE7F9E7' }
          }
          totalCell.font = { color: { argb: 'FF67C23A' }, bold: true, size: 12 }
        } else if (totalScore >= 80) {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFE1F3FF' }
          }
          totalCell.font = { color: { argb: 'FF409EFF' }, bold: true, size: 12 }
        } else if (totalScore >= 60) {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFEF7E7' }
          }
          totalCell.font = { color: { argb: 'FFE6A23C' }, bold: true, size: 12 }
        } else {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFEF0F0' }
          }
          totalCell.font = { color: { argb: 'FFF56C6C' }, bold: true, size: 12 }
        }
        
        // 等级单元格
        const levelCell = row.getCell(11)
        const levelColors = {
          '优秀': { bg: 'FFE7F9E7', fg: 'FF67C23A' },
          '良好': { bg: 'FFE1F3FF', fg: 'FF409EFF' },
          '中等': { bg: 'FFFEF7E7', fg: 'FFE6A23C' },
          '及格': { bg: 'FFFEF7E7', fg: 'FFE6A23C' },
          '不及格': { bg: 'FFFEF0F0', fg: 'FFF56C6C' }
        }
        const levelColor = levelColors[grade.gradeLevel]
        if (levelColor) {
          levelCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: levelColor.bg }
          }
          levelCell.font = { color: { argb: levelColor.fg }, bold: true }
        }
        
        // 及格列
        const passCell = row.getCell(12)
        if (grade.isPass) {
          passCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFE7F9E7' }
          }
          passCell.font = { color: { argb: 'FF67C23A' }, bold: true }
        } else {
          passCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFEF0F0' }
          }
          passCell.font = { color: { argb: 'FFF56C6C' }, bold: true }
        }
      }
      
      // 斑马纹效果
      if (index % 2 === 1) {
        for (let i = 1; i <= 15; i++) {
          const cell = row.getCell(i)
          if (!cell.fill || !cell.fill.fgColor) {
            cell.fill = {
              type: 'pattern',
              pattern: 'solid',
              fgColor: { argb: 'FFF9FAFB' }
            }
          }
        }
      }
    })
    
    // 添加边框
    sheet1.eachRow((row, rowNumber) => {
      if (rowNumber >= 1) {
        row.eachCell((cell) => {
          cell.border = {
            top: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            left: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            bottom: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            right: { style: 'thin', color: { argb: 'FFD0D0D0' } }
          }
        })
      }
    })
    
    // ================ 工作表2：统计分析 ================
    const sheet2 = workbook.addWorksheet('统计分析')
    
    // 设置列宽
    sheet2.columns = [
      { width: 25 },  // 统计项
      { width: 20 }   // 统计值
    ]
    
    // 添加标题
    sheet2.mergeCells('A1:B1')
    const statTitleCell = sheet2.getCell('A1')
    statTitleCell.value = '成绩统计分析'
    statTitleCell.font = { bold: true, size: 18, color: { argb: 'FF2C3E50' } }
    statTitleCell.alignment = { vertical: 'middle', horizontal: 'center' }
    statTitleCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFF0F2F5' }
    }
    sheet2.getRow(1).height = 40
    
    // 添加空行
    sheet2.addRow([])
    
    // 基本统计信息
    const basicStats = [
      { label: '学期', value: filterForm.semester || '2024春季' },
      { label: '课程', value: courseName },
      { label: '班级', value: clazzName || '全部班级' },
      { label: '学生总数', value: gradeStats.value.totalStudents },
      { label: '平均分', value: gradeStats.value.averageScore },
      { label: '及格率', value: gradeStats.value.passRate + '%' },
      { label: '优秀率 (≥90分)', value: gradeStats.value.excellentRate + '%' },
      { label: '导出时间', value: new Date().toLocaleString('zh-CN') },
      { label: '导出教师', value: teacherName }
    ]
    
    basicStats.forEach((stat, index) => {
      const row = sheet2.addRow([stat.label, stat.value])
      row.height = 30
      
      // 标签列样式
      row.getCell(1).font = { bold: true, size: 12 }
      row.getCell(1).alignment = { vertical: 'middle', horizontal: 'right' }
      row.getCell(1).fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFF5F7FA' }
      }
      
      // 值列样式
      row.getCell(2).font = { size: 12, color: { argb: 'FF2C3E50' }, bold: true }
      row.getCell(2).alignment = { vertical: 'middle', horizontal: 'left' }
      
      // 添加边框
      row.eachCell((cell) => {
        cell.border = {
          top: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          left: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          bottom: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          right: { style: 'thin', color: { argb: 'FFD0D0D0' } }
        }
      })
    })
    
    // 添加空行
    sheet2.addRow([])
    sheet2.addRow([])
    
    // 分数段分布
    sheet2.mergeCells(`A${sheet2.rowCount + 1}:B${sheet2.rowCount + 1}`)
    const scoreTitleCell = sheet2.getCell(`A${sheet2.rowCount}`)
    scoreTitleCell.value = '分数段分布'
    scoreTitleCell.font = { bold: true, size: 14, color: { argb: 'FF2C3E50' } }
    scoreTitleCell.alignment = { vertical: 'middle', horizontal: 'center' }
    scoreTitleCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE8F4F8' }
    }
    sheet2.getRow(sheet2.rowCount).height = 30
    
    // 添加分数段表头
    const scoreHeaderRow = sheet2.addRow(['分数段', '人数'])
    scoreHeaderRow.height = 25
    scoreHeaderRow.font = { bold: true, size: 11, color: { argb: 'FFFFFFFF' } }
    scoreHeaderRow.alignment = { vertical: 'middle', horizontal: 'center' }
    scoreHeaderRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF667EEA' }
    }
    
    // 计算分数段分布
    const scoreRanges = {
      '90-100分（优秀）': 0,
      '80-89分（良好）': 0,
      '70-79分（中等）': 0,
      '60-69分（及格）': 0,
      '0-59分（不及格）': 0
    }
    
    gradeList.value.forEach(grade => {
      const score = parseFloat(grade.totalScore)
      if (!isNaN(score)) {
        if (score >= 90) scoreRanges['90-100分（优秀）']++
        else if (score >= 80) scoreRanges['80-89分（良好）']++
        else if (score >= 70) scoreRanges['70-79分（中等）']++
        else if (score >= 60) scoreRanges['60-69分（及格）']++
        else scoreRanges['0-59分（不及格）']++
      }
    })
    
    // 添加分数段数据
    Object.entries(scoreRanges).forEach(([range, count], index) => {
      const row = sheet2.addRow([range, count])
      row.height = 24
      row.getCell(1).alignment = { vertical: 'middle', horizontal: 'left' }
      row.getCell(2).alignment = { vertical: 'middle', horizontal: 'center' }
      row.getCell(2).font = { bold: true, color: { argb: 'FF409EFF' }, size: 12 }
      
      // 根据分数段设置颜色
      if (range.includes('优秀')) {
        row.getCell(1).fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFE7F9E7' }
        }
      } else if (range.includes('良好')) {
        row.getCell(1).fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFE1F3FF' }
        }
      } else if (range.includes('不及格')) {
        row.getCell(1).fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFFEF0F0' }
        }
      } else if (index % 2 === 1) {
        row.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFF9FAFB' }
        }
      }
      
      // 添加边框
      row.eachCell((cell) => {
        cell.border = {
          top: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          left: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          bottom: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          right: { style: 'thin', color: { argb: 'FFD0D0D0' } }
        }
      })
    })
    
    // 生成文件名
    const semester = filterForm.semester || '2024春季'
    const courseFilter = courseName !== '全部课程' ? `_${courseName}` : ''
    const clazzFilter = clazzName ? `_${clazzName}` : ''
    const fileName = `成绩表_${semester}${courseFilter}${clazzFilter}_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`
    
    // 导出文件
    const buffer = await workbook.xlsx.writeBuffer()
    const blob = new Blob([buffer], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success(`成功导出 ${gradeList.value.length} 条成绩数据！`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 初始化
onMounted(() => {
  initData()
  fetchGradeList()
})
</script>

<style scoped>
.teacher-grade {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
  min-height: 100vh;
  font-size: 16px;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 36px;
  font-weight: 700;
  letter-spacing: 1px;
}

.page-subtitle {
  margin: 0;
  color: #606266;
  font-size: 16px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: none;
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 16px;
  margin-right: 16px;
}

.filter-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 15px;
}

.filter-form :deep(.el-button) {
  font-size: 15px;
  padding: 10px 20px;
}

.filter-form :deep(.el-input__inner) {
  font-size: 15px;
}

.filter-form :deep(.el-select) {
  font-size: 15px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.stat-card :deep(.el-card__body) {
  padding: 24px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 32px;
  flex-shrink: 0;
}

.stat-card-1 .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card-2 .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-card-3 .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card-4 .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 40px;
  font-weight: 800;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.action-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.action-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.action-card :deep(.el-button) {
  font-size: 15px;
  padding: 10px 20px;
}

.grade-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.grade-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  color: #ffffff;
  font-weight: 600;
  font-size: 18px;
}

.grade-content {
  padding: 0;
}

.grade-content :deep(.el-table) {
  font-size: 16px;
}

.grade-content :deep(.el-table th) {
  background: #f5f7fa;
  color: #2c3e50;
  font-weight: 600;
  padding: 14px 0;
  font-size: 16px;
}

.grade-content :deep(.el-table td) {
  padding: 12px 0;
  font-size: 16px;
}

.grade-content :deep(.el-button) {
  font-size: 15px;
}

.grade-content :deep(.el-button--small) {
  font-size: 15px;
  padding: 8px 15px;
}

.grade-content :deep(.el-button--small.is-link) {
  padding: 6px 10px;
  margin: 0 1px;
  white-space: nowrap;
}

.grade-content :deep(.el-button--danger.is-link) {
  color: #f56c6c;
  font-weight: 600;
}

.grade-content :deep(.el-button--danger.is-link:hover) {
  color: #f56c6c;
  background-color: #fef0f0;
}

.grade-content :deep(.el-button--primary.is-link) {
  color: #409eff;
  font-weight: 600;
}

.grade-content :deep(.el-button--info.is-link) {
  color: #909399;
  font-weight: 600;
}

.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.pagination-container :deep(.el-pagination) {
  font-size: 15px;
}

.pagination-container :deep(.el-pagination__total) {
  font-size: 15px;
}

.pagination-container :deep(.el-pagination__jump) {
  font-size: 15px;
}

/* 标签字体 */
:deep(.el-tag) {
  font-size: 14px;
  padding: 4px 10px;
}

/* 分数样式 */
.score-excellent {
  color: #67c23a;
  font-weight: 700;
  font-size: 16px;
}

.score-good {
  color: #409eff;
  font-weight: 700;
  font-size: 16px;
}

.score-pass {
  color: #e6a23c;
  font-weight: 700;
  font-size: 16px;
}

.score-fail {
  color: #f56c6c;
  font-weight: 700;
  font-size: 16px;
}

/* 批量录入行样式 */
:deep(.row-excellent) {
  background: #f0f9ff !important;
}

:deep(.row-pass) {
  background: #fefce8 !important;
}

:deep(.row-fail) {
  background: #fef2f2 !important;
}

/* 内联编辑样式 */
.grade-content :deep(.el-table__row.editing-row) {
  background: #f0f9ff !important;
  border-left: 3px solid #409eff;
}

.grade-content :deep(.el-table__row.editing-row td) {
  background: #f0f9ff !important;
}

.grade-content :deep(.el-input-number) {
  width: 100%;
}

.grade-content :deep(.el-input-number .el-input__inner) {
  text-align: center;
  font-size: 15px;
}

:deep(.el-input-number__increase),
:deep(.el-input-number__decrease) {
  font-size: 14px;
}

:deep(.el-switch__label) {
  font-size: 14px;
}

.batch-input-container {
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-footer :deep(.el-button) {
  font-size: 15px;
  padding: 10px 24px;
}

/* 对话框内表单元素字体 */
:deep(.el-dialog__body) {
  font-size: 15px;
}

:deep(.el-form-item__label) {
  font-size: 15px;
}

:deep(.el-input__inner) {
  font-size: 15px;
}

:deep(.el-textarea__inner) {
  font-size: 15px;
}

:deep(.el-select .el-input__inner) {
  font-size: 15px;
}

:deep(.el-descriptions__label) {
  font-size: 15px;
}

:deep(.el-descriptions__content) {
  font-size: 15px;
}

:deep(.el-alert__title) {
  font-size: 15px;
}

:deep(.el-alert__description) {
  font-size: 14px;
}

:deep(.el-alert__description p) {
  font-size: 14px;
  line-height: 1.8;
}

:deep(.el-statistic__head) {
  font-size: 15px;
}

:deep(.el-statistic__number) {
  font-size: 28px;
}

:deep(.el-link) {
  font-size: 15px;
}

:deep(.el-upload__tip) {
  font-size: 14px;
}

:deep(.el-select-dropdown__item) {
  font-size: 15px;
  padding: 10px 20px;
}

:deep(.el-option) {
  font-size: 15px;
}

:deep(.el-message) {
  font-size: 15px;
}

:deep(.el-message-box__title) {
  font-size: 16px;
}

:deep(.el-message-box__content) {
  font-size: 15px;
}

:deep(.el-divider__text) {
  font-size: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .teacher-grade {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .stat-card :deep(.el-card__body) {
    padding: 16px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .stat-icon {
    width: 56px;
    height: 56px;
    font-size: 24px;
  }
  
  .stat-value {
    font-size: 28px;
  }
}
</style>
